/**
 * @description 事件总线
 * @export
 * @class EventBus
 */
class EventBus {
  eventCenter: {
    [key: string]: ((e?: any) => void)[];
  } = {};
  constructor() {}

  /**
   * @description 加入事件响应
   * @memberof EventBus
   */
  add<T = undefined>(eventName: string, callback: (e: T) => void): void {
    if (!this.eventCenter[eventName]) {
      this.eventCenter[eventName] = [];
    }
    this.eventCenter[eventName].push(callback);
  }

  /**
   * @description 触发事件
   * @param {string} eventName
   * @memberof EventBus
   */
  emit(eventName: string, props?: any): void {
    if (!this.eventCenter[eventName]) {
      return;
    }
    this.eventCenter[eventName].forEach((callback) => {
      callback(props);
    });
  }

  off(eventName: string, callback: () => void): void {
    if (!this.eventCenter[eventName]) {
      console.log(`there is no event trigger like '${eventName}'`);
      return;
    }
    const cbs = this.eventCenter[eventName].filter((i) => i !== callback);
    this.eventCenter[eventName] = cbs;
  }
}

export default new EventBus();
